package com.xxq.aidlserver;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AidlService extends Service {

    public final String mNewsURL = "https://news.sina.com.cn/world/";

    private IBinder mBinder = new NewsBinder();
    private List<NewsInfo> mNewsList = new ArrayList<NewsInfo>();

    public AidlService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        //当客户端调用bindService()以连接此服务时
        //客户端的 onServiceConnected()回调方法会接收该服务onBind()方法
        //返回的mBinder实例
        //否则绑定服务时客户端崩溃报错：
        // Caused by: java.lang.NullPointerException:
        // Attempt to invoke interface method
        // 'java.lang.String com.xxq.aidlserver.IListNews.queryNews(int)' on a null object reference
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("AidlService", "onCreate()");
        System.out.println("开启远程服务");

        getLatestNewsList(mNewsURL);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("AidlService", "onStartCommand()");

        return super.onStartCommand(intent, flags, startId);
    }

    private final class NewsBinder extends IAidlInterface.Stub {
        @Override
        public List<NewsInfo> getNewsList() {
            getLatestNewsList(mNewsURL);
            return mNewsList;
        }
    }

    private void getLatestNewsList(String url) {
        System.out.println("开始解析网页");
        try {
            Document doc = Jsoup.connect(url)
                    .userAgent("Mozilla")
                    .timeout(3000)
                    .get();

            Elements elements = doc.select(".news-item");

            if (!elements.isEmpty()) {
                for (Element element : elements) {
                    Elements h2Tags = element.getElementsByTag("h2");
                    if (h2Tags.size() > 0) {

                        Element time = element.select(".time").first();
                        String newsTime = time.text();

                        Element a = element.select("a[href]").first();
                        String newsTitle = a.text();
                        String newsUrl = a.attr("href");

                        System.out.println(newsTime + " " + newsTitle + " " + newsUrl);

                        NewsInfo news = new NewsInfo(newsTitle, newsUrl, newsTime);
                        mNewsList.add(news);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }
    }
}
